package com.xbongbong.saas.help.workflow;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CloneUtil;
import com.xbongbong.pro.contractperformance.pojo.ContractPerformanceLogPojo;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.domain.entity.ContractPerformanceEntity;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.model.ContractPerformanceModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 *
 * @author 魏荣杰
 *
 */
@Component
public class ContractPerformanceHelp {

    @Resource
    private UserModel userModel;
    @Resource
    private ContractPerformanceModel contractPerformanceModel;

    /**
     * Description: 在新建、编辑时根据签订人改变业绩归属，若没有业绩分配创建一条当前签订人的100%的业绩分配，若签订人改变，当前签订人替换原签订人的业绩分配
     *
     * @param corpid 公司id
     * @param contractId 合同id
     * @param data 数据
     * @param contractPerformanceLogList 操作日志
     * @return void
     * @throws
     * @author 魏荣杰
     * @date 2021/7/20 20:29
     * @since
     */
    public void changeContractPerformance(String corpid, Long contractId, JSONObject data, List<ContractPerformanceLogPojo> contractPerformanceLogList) throws XbbException {
        String signUserId = FastJsonHelper.getStringFromFormData(data, ContractEnum.SIGN_PERSON.getAttr());
        UserEntity signPersonUser = userModel.getByKeyIngoreDel(signUserId, corpid);
        if(signPersonUser == null){
            return;
        }
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put("contractId", contractId);
        param.put("delIn", Arrays.asList(DelEnum.NORMAL.getDel(), DelEnum.APPROVE_STATUS.getDel()));
        //业绩分配列表
        List<ContractPerformanceEntity> performanceList = contractPerformanceModel.findEntitys(param);
        try {
            if (performanceList.isEmpty()) {
                ContractPerformanceEntity performance = new ContractPerformanceEntity();
                performance.setCorpid(corpid);
                performance.setContractId(contractId);
                performance.setUserId(signPersonUser.getUserId());
                performance.setUserName(signPersonUser.getName());
                performance.setUserAvatar(signPersonUser.getAvatar());
                performance.setIsSign(BasicConstant.ONE);
                performance.setRate(100D);
                contractPerformanceModel.insert(performance);

                ContractPerformanceLogPojo logPojo = new ContractPerformanceLogPojo();
                logPojo.setNewEntity(performance);
                contractPerformanceLogList.add(logPojo);
            } else {
                // 前签订人
                ContractPerformanceEntity oldPerformance = null;
                // 现签订人
                ContractPerformanceEntity signPerformance = null;
                for(ContractPerformanceEntity performance : performanceList){
                    if(Objects.equals(performance.getIsSign(),BasicConstant.ONE)){
                        oldPerformance = performance;
                    }
                    if(Objects.equals(performance.getUserId(), signPersonUser.getUserId())){
                        signPerformance = performance;
                    }
                }
                // 前签订人和当前签订人不同，转移业绩分配
                if(Objects.nonNull(oldPerformance)  && !Objects.equals(oldPerformance.getUserId(), signPersonUser.getUserId())){
                    ContractPerformanceEntity oldSignPerformance = null;
                    Double rate = oldPerformance.getRate();
                    if(Objects.nonNull(signPerformance)){
                        rate += signPerformance.getRate();
                        oldSignPerformance = (ContractPerformanceEntity)CloneUtil.deepClone(signPerformance);
                    }
                    if (Objects.isNull(signPerformance)){
                        signPerformance = new ContractPerformanceEntity();
                        signPerformance.setCorpid(corpid);
                        signPerformance.setContractId(contractId);
                        signPerformance.setUserId(signPersonUser.getUserId());
                        signPerformance.setUserName(signPersonUser.getName());
                        signPerformance.setUserAvatar(signPersonUser.getAvatar());
                        signPerformance.setIsSign(BasicConstant.ONE);
                        signPerformance.setRate(rate);
                    } else {
                        signPerformance.setIsSign(BasicConstant.ONE);
                        signPerformance.setRate(rate);
                    }
                    contractPerformanceModel.save(signPerformance);
                    contractPerformanceModel.deleteByKey(oldPerformance.getId(), corpid);

                    ContractPerformanceLogPojo saveLogPojo = new ContractPerformanceLogPojo();
                    saveLogPojo.setNewEntity(signPerformance);
                    if (Objects.nonNull(oldSignPerformance)) {
                        saveLogPojo.setOldEntity(oldSignPerformance);
                    }
                    ContractPerformanceLogPojo delLogPojo = new ContractPerformanceLogPojo();
                    delLogPojo.setOldEntity(oldPerformance);
                    contractPerformanceLogList.add(saveLogPojo);
                    contractPerformanceLogList.add(delLogPojo);
                }
                List<ContractPerformanceEntity> updateDelList = new ArrayList<>();
                contractPerformanceModel.setDelByContractId(contractId, corpid, DelEnum.NORMAL.getDel(), updateDelList);
                updateDelList.forEach(item -> {
                    ContractPerformanceLogPojo logPojo = new ContractPerformanceLogPojo();
                    ContractPerformanceEntity newItem = (ContractPerformanceEntity)CloneUtil.deepClone(item);
                    newItem.setDel(DelEnum.NORMAL.getDel());
                    logPojo.setOldEntity(item);
                    logPojo.setNewEntity(newItem);
                    contractPerformanceLogList.add(logPojo);
                });
            }
        } catch (XbbException e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }
}
